package com.lishilin.gulimall.ware.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lishilin.common.constant.WareConstant;
import com.lishilin.common.utils.PageUtils;
import com.lishilin.common.utils.Query;
import com.lishilin.gulimall.ware.dao.PurchaseDao;
import com.lishilin.gulimall.ware.entity.PurchaseDetailEntity;
import com.lishilin.gulimall.ware.entity.PurchaseEntity;
import com.lishilin.gulimall.ware.service.PurchaseDetailService;
import com.lishilin.gulimall.ware.service.PurchaseService;
import com.lishilin.gulimall.ware.service.WareSkuService;
import com.lishilin.gulimall.ware.vo.MergeVo;
import com.lishilin.gulimall.ware.vo.PurchaseDoneVo;
import com.lishilin.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService detailService;

    @Autowired
    WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params),wrapper);

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo vo) {
        Long purchaseId = vo.getPurchaseId();//如果不为空则使用前端传来的采购单id
        if (purchaseId==null) {//没有提交采购单的时候先新建一个采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PuchaseStatusEnum.CREATED.getCode());//采购单状态默认为新建
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            //新建完成采购单之后就可以获取得到采购单的id
            purchaseId = purchaseEntity.getId();
        }
        //todo 确认采购单状态是0,1才可以合并

        List<Long> items = vo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(i -> {
            PurchaseDetailEntity detai = new PurchaseDetailEntity();
            detai.setId(i);
            detai.setPurchaseId(finalPurchaseId);
            detai.setStatus(WareConstant.PuchaseDetailStatusEnum.ASSIGNED.getCode());
            return detai;
        }).collect(Collectors.toList());
        detailService.updateBatchById(purchaseDetailEntities);
        PurchaseEntity purchaseEntity1 = new PurchaseEntity();
        purchaseEntity1.setId(purchaseId);
        purchaseEntity1.setUpdateTime(new Date());
        this.updateById(purchaseEntity1);
    }

    @Override
    public void received(List<Long> ids) {
        //1.确认当前采购单是新建或已分配状态
        List<PurchaseEntity> purchaseEntities = ids.stream().map(item -> { //获取采购状态是新建或者已分配状态的采购单
            PurchaseEntity purchaseEntity = this.getById(item);//根据id获取采购单
            return purchaseEntity;
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PuchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PuchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).map(item->{
            item.setStatus(WareConstant.PuchaseStatusEnum.RECEIVE.getCode());//将采购单状态设置为已领取
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //2.改变采购单的状态
        this.updateBatchById(purchaseEntities);
        //3.改变采购需求的状态
        purchaseEntities.forEach(item->{// 假如有两个采购单  [2,3] 查询2号采购单下有几个采购项  再查3号
            List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(item.getId());//根据采购单的id查询出当前采购单下有哪些采购项
            List<PurchaseDetailEntity> collect = entities.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PuchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(collect);
        });
    }

    @Transactional()
    @Override
    public void done(PurchaseDoneVo vo) {

        Long id = vo.getId();

        //2.改变采购项的状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = vo.getItems();

        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();

            if (item.getStatus() == WareConstant.PuchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                purchaseDetailEntity.setStatus(item.getStatus());
            } else {
                purchaseDetailEntity.setStatus(item.getStatus());
                //3.将成功采购的进行入库
                //每一个采购项采购完成了都需要将它入库处理
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());//先查出采购项的详细信息
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());//设置采购项的id
            updates.add(purchaseDetailEntity);
        }
        detailService.updateBatchById(updates);//根据采购项的id批量更新采购项的状态
        //1.改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PuchaseStatusEnum.FINISH.getCode():
                WareConstant.PuchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);



    }


}